<template>
  <div>
    <el-upload class="avatar-uploader"
               ref="upImageRef"
               action="http://localhost:3000/student/studentImg"
               :show-file-list="false"
               :auto-upload="false"
               :on-change="upImg">
      <el-button size="mini"
                 style="float: left; padding: 3px 0"
                 type="text">点击上传一寸照</el-button>
    </el-upload>
  </div>
</template>

<script>

export default {
  name: 'upImage',
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    async upImg (file) {
      console.log('wenjian', file)
      const imgType = ['jpg', 'png']
      const types = file.name.split('.')[1]
      const isTrueType = imgType.some(valid => valid === types)
      const isTrueSize = file.size / 1024 / 1024 < 0.7
      if (!isTrueType) {
        this.$message.error('上传的一寸照只能是 JPG或PNG 格式，且名字不能存在符号’.‘！')
        return isTrueType
      } else {
        if (!isTrueSize) {
          this.$message.error('上传头像图片大小不能超过 640KB!')
          return isTrueSize
        } else {
          const reader = new FileReader()
          // const imgFile = URL.createObjectURL(file.raw)
          reader.readAsDataURL(file.raw)
          // console.log(reader.readAsDataURL(file.raw))
          reader.onload = (e) => {
            // console.log(e)
            const imgBase64 = e.target.result
            this.imageUrl = imgBase64
            // 发送事件给父组件
            this.$emit('getUserImg', this.imageUrl)
          }
        }
      }
    },
    clearFiles () {
      this.$refs.upImageRef.clearFiles()
    }
  }
}

</script>
<style  scoped>
</style>
